package cn.aifeix.order.service.impl;

import cn.aifeix.basic.config.BussinessException;
import cn.aifeix.basic.util.PageList;
import cn.aifeix.order.domain.OrderProduct;
import cn.aifeix.order.mapper.OrderProductMapper;
import cn.aifeix.order.query.OrderProductQuery;
import cn.aifeix.order.service.IOrderProductService;
import cn.aifeix.basic.service.impl.BaseServiceImpl;
import cn.aifeix.org.domain.Employee;
import cn.aifeix.org.service.EmployeeService;
import cn.aifeix.pet.dto.AcceptOrderFormDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aifeix
 * @since 2022-11-03
 */
@Service
public class OrderProductServiceImpl extends BaseServiceImpl<OrderProduct> implements IOrderProductService {

    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private EmployeeService employeeService;


    @Override
    public PageList<OrderProduct> toHandle(OrderProductQuery query) {
        // 查询总条数
        Integer totals = orderProductMapper.findByParamCount(query);
        if (null == totals || 0 == totals){
            return new PageList<>(0,new ArrayList<OrderProduct>());
        }

        // 查询数据
        List<OrderProduct> orderProducts = orderProductMapper.findByParam(query);
        return new PageList<>(totals, orderProducts);
    }

    @Override
    public void reject(Long id, Employee employee) {
        OrderProduct orderProduct = orderProductMapper.findById(id);
        if (orderProduct == null) {
            throw new BussinessException("订单不存在");
        }
        orderProduct.setState(-2);
        orderProductMapper.update(orderProduct);
    }

    @Override
    public void confirm(Long id) {
        OrderProduct orderProduct = orderProductMapper.findById(id);
        orderProduct.setState(2);
        orderProductMapper.update(orderProduct);
    }

    @Override
    public void cancel(Long id) {
        OrderProduct orderProduct = orderProductMapper.findById(id);
        orderProduct.setState(-1);
        orderProductMapper.update(orderProduct);
    }

    @Override
    public void accept(AcceptOrderFormDto dto) {
        OrderProduct orderProduct = orderProductMapper.findById(dto.getMsgId());
        if (orderProduct == null) {
            throw new BussinessException("订单不存在");
        }
        // 3.需要解决线程安全问题
        synchronized (orderProduct.getId()){
            Employee employee = employeeService.findById(dto.getHandler());
            if (employee == null){
                throw new BussinessException("不存在此员工，请重新操作！");
            }
            if (orderProduct.getState() == 0){
                orderProduct.setState(1);
                orderProductMapper.update(orderProduct);

            }
        }
    }
}
